package org.example.auth.config.oauth.granter;

import com.alibaba.fastjson.JSON;
import org.example.auth.domain.SocialLoginBody;
import org.example.common.core.constants.Constants;
import org.example.common.core.enums.GrantUser;
import org.example.common.core.exception.base.BaseException;
import org.example.common.social.config.properties.SocialProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 第三方授权登录
 */
public class SocialTokenGranter extends AbstractTokenGranter {

    private static Logger logger= LoggerFactory.getLogger(SocialTokenGranter.class);

    private static final String GRANT_TYPE = "social";
    private static final String GRANT_USER = Constants.GRANT_USER;
    private static final String DEVICE_TYPE = Constants.DEVICE_TYPE;


    private final AuthenticationManager authenticationManager;

    public SocialTokenGranter(AuthenticationManager authenticationManager,
                              AuthorizationServerTokenServices tokenServices,
                              ClientDetailsService clientDetailsService,
                              OAuth2RequestFactory requestFactory
                              ) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    protected SocialTokenGranter(AuthenticationManager authenticationManager,
                                 AuthorizationServerTokenServices tokenServices,
                                 ClientDetailsService clientDetailsService,
                                 OAuth2RequestFactory requestFactory,
                                 String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String,String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        SocialLoginBody socialLoginBody= JSON.parseObject(JSON.toJSONString(parameters), SocialLoginBody.class);
        //获取认证标识
        Map<String,Object> additionalInformation= client.getAdditionalInformation();
        if(ObjectUtils.isEmpty(additionalInformation))  throw new BaseException("客户端参数错误");
        String user_type =(String)additionalInformation.get(GRANT_USER);
        String device_type =(String)client.getAdditionalInformation().get(DEVICE_TYPE);
        GrantUser grantUser= GrantUser.valueOf(user_type.toUpperCase());
        socialLoginBody.setGrant_user(grantUser);
        socialLoginBody.setExpires_in(client.getAccessTokenValiditySeconds());
        socialLoginBody.setGrant_type(GRANT_TYPE);
        socialLoginBody.setDevice_type(device_type);
        socialLoginBody.setClient_Id(client.getClientId());
        Authentication userAuth = new UsernamePasswordAuthenticationToken(socialLoginBody.getSocialCode(), null);
        ((AbstractAuthenticationToken) userAuth).setDetails(socialLoginBody);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        }
        catch (Exception ase) {
            throw new InvalidGrantException(ase.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: "+client.getClientId());
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }







}
